package com.retry.task.admin.base.datasource;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author gao.gwq
 * @version 1.0
 * @date 2021/9/2  5:00 下午
 * @Description TODO
 */
@Configuration
@EnableConfigurationProperties({DatasourceProperties.class})
public class RetryTddlDataSourceConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(RetryTddlDataSourceConfigurer.class);

    @Autowired
    private DatasourceProperties datasourceProperties;

    /**
     * 注解{@link Bean}里面的{@link Bean#initMethod()}和{@link Bean#destroyMethod()}不能缺少
     *
     * @return
     */
    @Primary
    @Bean(name = "retryTaskDataSource", initMethod = "init", destroyMethod = "close")
    public DataSource retryTaskDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();

        BeanUtils.copyProperties(datasourceProperties, druidDataSource);
        druidDataSource.setUrl(datasourceProperties.getUrl());
        druidDataSource.setPassword(datasourceProperties.getPassword());
        druidDataSource.setUsername(druidDataSource.getUsername());
        druidDataSource.setValidationQuery(druidDataSource.getValidationQuery());
        druidDataSource.setDriverClassName(datasourceProperties.getDriverClassName());
        return druidDataSource;
    }

    @Bean(name = "retryTaskTransactionManager")
    public PlatformTransactionManager tddlTranceManager(@Qualifier("retryTaskDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "retryTaskTransactionTemplate")
    public TransactionTemplate transactionTemplate(
        @Qualifier("retryTaskTransactionManager") PlatformTransactionManager platformTransactionManager) {
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        transactionTemplate.setTransactionManager(platformTransactionManager);
        transactionTemplate.setIsolationLevelName("ISOLATION_DEFAULT");
        transactionTemplate.setPropagationBehaviorName("PROPAGATION_REQUIRED");
        return transactionTemplate;
    }
}